import React from 'react';
import Taro from '@tarojs/taro';
import {connect} from 'react-redux';
import {View, Button, Image, ScrollView} from '@tarojs/components';
import {AtActionSheet} from 'taro-ui';

import * as T from '../../types';
import actions from '../../actions/index';
import {store2Props} from '../../selectors';
import {OSS_PATH_PREFIX, OSS_BASE_PATH_PREFIX, GAME_TYPE, CODE_SUCCESS, IMAGE_EMPTY} from '../../constant';
type IInfoProps = T.IProps & T.IInfoProps;
import PageLoading from '../../../../common/PageLoading';

import './WishModal.less';
import 'taro-ui/dist/style/components/action-sheet.scss';
import 'taro-ui/dist/style/components/flex.scss';
// @ts-ignore
@connect<Partial<IInfoProps>, T.IInfoState>(store2Props, actions)
/**
 * 许愿模态框
 */
export default class WishModal extends React.Component<Partial<IInfoProps>, T.IInfoState> {
  // 使用state值
  constructor(props) {
    super(props);
    this.state = {
      pics: {
        closeIcon: OSS_PATH_PREFIX + '/taskClose.png',
        emptyIcon: OSS_BASE_PATH_PREFIX + '/empty.png',
      },

      selectId: -1,
      empty: {
        text: '许愿池努力填满中...',
      },
      loading: {
        status: false,
        text: '',
        style: {},
      },
      imageError: {}, // 错误图片
    };
  }

  componentWillReceiveProps(nextProps: Readonly<Partial<IInfoProps>>, nextContext: any): void {
    if (nextProps.visible == true && this.props.visible == false && nextProps.main.status.loadingProduct == true) {
      this.setState({
        loading: {
          ...this.state.loading,
          status: true,
        },
      });
    }

    if (nextProps.main.status.loadingProduct == false && this.props.main.status.loadingProduct == true) {
      this.setState({
        loading: {
          ...this.state.loading,
          status: false,
        },
      });
    }

    // 添加许愿
    if (nextProps.main.status.creatingWish == false && this.props.main.status.creatingWish == true) {
      let label =
        nextProps.main.codeMessage == '操作成功' || !nextProps.main.codeMessage
          ? '许愿成功'
          : nextProps.main.codeMessage;
      Taro.showToast({
        title: label,
        icon: 'none',
        duration: 2000,
      });

      // 查询游戏基本信息
      if (nextProps.main.response.createWish == CODE_SUCCESS) {
        this.props.onQueryGame();
        this.props.onCancel(); // 取消模态框
      }
    }

    // 取消许愿
    if (nextProps.main.status.cancelingWish == false && this.props.main.status.cancelingWish == true) {
      let label = nextProps.main.codeMessage == '操作成功' ? '取消许愿成功' : nextProps.main.codeMessage;
      Taro.showToast({
        title: label,
        icon: 'none',
        duration: 2000,
      });

      if (nextProps.main.response.cancelWish == CODE_SUCCESS) {
        this.props.onQueryGame();
      }
    }

    // 查询游戏基本信息
    if (nextProps.main.status.loadingGameInfo == false && this.props.main.status.loadingGameInfo == true) {
      let currentWish = nextProps.main.currentWish;
      this.setState({
        selectId: currentWish && currentWish.goodsInfoId ? currentWish.goodsInfoId : -1,
      });
    }
  }

  /**
   * 渲染
   * @returns
   */
  render() {
    let {
      main: {
        productItems,
        status: {loadingProduct},
      },
      visible,
      actions: {action},
      navbarSettings
    } = this.props;

    const {
      loading: {status},
    } = this.state;
    console.log('wishmodal render selectId', this.state.selectId);

    console.log('wishModal render visible', this.props.wishItem);
    console.log('wishModal render loadingProduct=', loadingProduct);
    console.log('wishModal productItems', productItems);
    console.log('wishmodal render status', status);
    return (
      <AtActionSheet isOpened={visible} className="wishModal" onClose={this.handleCancel} atActionSheetStyle={{top: navbarSettings.navBarHeight}}>
        <View className="wishTitle">许愿商店</View>
        {this.renderCloseIcon()}
        {productItems.length > 0 ? (
          <>
            {this.renderSelectProductContent()}
            {this.renderProductListContent(productItems)}
            {this.renderOperateContent()}
          </>
        ) : (
          this.renderEmptyContent()
        )}
      </AtActionSheet>
    );
  }

  /**
   * 渲染加载动画
   * @returns
   */
  renderLoadingContent() {
    const {
      pics: {loadingIcon},
      loading: {status, text, style},
    } = this.state;
    return (
      <View className="loadingContent">
        <PageLoading style={style} />
      </View>
    );
  }

  /**
   * 关闭按钮
   */
  renderCloseIcon() {
    const {pics} = this.state;
    return (
      <View className="modalClose" onClick={this.handleCancel}>
        <Image src={pics.closeIcon} className="closeIcon" />
      </View>
    );
  }

  /**
   * 关闭模态框
   */
  handleCancel = () => {
    console.log('wishModal handleCancel onCancel');
    this.props.onCancel();
  };

  /**
   * 渲染选中许愿布局
   */
  renderSelectProductContent() {
    const {selectId} = this.state;
    const {
      main: {productItems},
    } = this.props;
    let currentItem = productItems.find((i, iIndex) => i.goodsInfoId == selectId);
    return (
      <View className="selector">
        {currentItem ? (
          <>
            <View className="selectName">{currentItem.goodsInfoName}</View>
            <Image src={currentItem.goodsInfoImg || IMAGE_EMPTY} className="gift" mode="aspectFit" />
          </>
        ) : (
          <></>
        )}
      </View>
    );
  }

  /**
   * 渲染商品列表内容
   */
  renderProductListContent(items) {
    console.log('wishModal renderProductListContent items', items);
    const {selectId} = this.state;

    return (
      <View className="product">
        <ScrollView className="list" scrollX scrollWithAnimation scrollTop={0}>
          <View className="content">
            {items.map((i: any, index: number) => (
              <View className="productItem" key={'product' + index}>
                <View
                  className="item"
                  onClick={() => this.handleSelectItem(i, index)}
                  style={{transform: `scale(${i.goodsInfoId == selectId ? 1.2 : 1})`}}
                >
                  <Image
                    src={i.goodsInfoImg || IMAGE_EMPTY}
                    className="thum"
                    mode="aspectFit"
                    onError={(e) =>
                      this.handleImageError(e, index, {
                        propName: 'productItems',
                        imageState: 'goodsInfoImg',
                      })
                    }
                  />
                  <View className="name">{i.goodsInfoName}</View>
                  <View className="singlePrice">{i.singlePrice}币/次</View>
                </View>
              </View>
            ))}
          </View>
        </ScrollView>
      </View>
    );
  }

  /**
   * 图片加载错误
   * @param e
   * @param index
   */
  handleImageError = (e, index, item) => {
    const {main} = this.props;
    const {propName, imageState} = item;
    let {imageError} = this.state;
    if (imageError[propName]) {
      imageError[propName] = imageError[propName].concat([index]);
    } else {
      imageError[propName] = [index];
    }
    let result = JSON.parse(JSON.stringify(main[propName]));
    let currentImage = imageError[propName];
    let ids = currentImage;
    ids.map((i) => {
      result[i] = {
        ...result[i],
        [imageState]: IMAGE_EMPTY,
      };
    });
    this.props.actions.action.commonChange('main.' + propName, result);
  };

  /**
   * 渲染空
   */
  renderEmptyContent() {
    const {
      pics: {emptyIcon},
      empty: {text},
    } = this.state;
    return (
      <View className="emptyContent">
        <Image src={emptyIcon} className="emptyIcon" />
        <View className="emptyExtraTitle">{text}</View>
      </View>
    );
  }

  /**
   * 选中item
   */
  handleSelectItem = (item, index) => {
    console.log('wishModal handleSelectItem item', item);
    const {
      main: {currentWish},
    } = this.props;

    // 已有选中的许愿则不能选择其他的，除非他取消
    if (currentWish && currentWish.id) {
      return;
    }

    this.setState({
      selectId: item.goodsInfoId,
    });
  };

  /**
   * 渲染操作内容
   * @returns
   */
  renderOperateContent() {
    const {
      main: {productItems, currentWish},
    } = this.props;
    return (
      <View className="operates">
        {productItems.length > 0 ? (
          <Button className="wishButton" onClick={this.handleWish}>
            {currentWish && currentWish.id ? '取消许愿' : '提交许愿'}
          </Button>
        ) : (
          <></>
        )}
      </View>
    );
  }

  /**
   * 点击许愿
   */
  handleWish = () => {
    const {selectId} = this.state;
    const {
      main: {productItems, currentWish, gameInfo},
    } = this.props;
    let currentItem = productItems.find((i, iIndex) => i.goodsInfoId == selectId);
    console.log('wishModal handleWish cyurrentitem', currentItem, 'productITEMS', productItems, 'selectId', selectId);

    if (selectId == -1) {
      Taro.showToast({
        title: '请先选择许愿商品再提交',
        icon: 'none',
        duration: 2000,
      });
      return;
    } else {
      console.log('wishModal handleWish currentItem', currentItem);

      let cancel = currentWish && currentWish.id ? true : false;

      if (!cancel) {
        // 判断库存是否足
        if (currentItem.remainingNum == 0) {
          Taro.showToast({
            title: '该商品库存不足,请选择其他商品',
            icon: 'none',
            duration: 2000,
          });
          return;
        }

        let params = {
          gameType: GAME_TYPE, // 2-魔力赏 3-魔力抓娃娃
          goodsInfoId: currentItem.goodsInfoId,
          goodsInfoImg: currentItem.goodsInfoImg,
          goodsInfoName: currentItem.goodsInfoName,
          ipId: gameInfo.ipId,
          price: currentItem.price,
          prizeConfigId: gameInfo.prizeConfigId,
        };

        console.log('wishModel params=', params);
        this.props.actions.action.createWishItem(params);
      } else {
        let params = {
          id: currentWish.id,
        };
        this.props.actions.action.cancelWishItem(params);
      }
    }
  };
}
